const ErrorResult = require('../config/handle')

const notnull = (obj, name = '参数') => {
  if (obj === undefined || obj === null || obj === '' || obj === {} || obj === []) {
    throw new ErrorResult(name + '不能为空', 400)
  }
}

const checkPhone = (phone) => {
  notnull(phone, '手机号')
  if (!phone.match(/^1[3456789]\d{9}$/)) {
    throw new ErrorResult('手机号错误', 400)
  }
}

const checkPassword = (password) => {
  notnull(password, '密码')
  if (!password.match(/^[a-zA-Z0-9]{6,20}$/)) {
    throw new ErrorResult('密码错误', 400)
  }
}

const checkRegister = (ctx) => {
  ctx.request.body.account = ctx.request.body.account.trim()
  ctx.request.body.password = ctx.request.body.password.trim()
  checkPhone(ctx.request.body.account)
  checkPassword(ctx.request.body.password)
}

const checkUserInfo = (ctx) => {
  ctx.request.body.name = ctx.request.body.name.trim()
  ctx.request.body.address = ctx.request.body.address.trim()
  ctx.request.body.logo = ctx.request.body.logo.map(item => item.trim())
  notnull(ctx.request.body.name, '店铺名称')
  notnull(ctx.request.body.address, '店铺地址')
  notnull(ctx.request.body.logo, '店铺logo')
}

module.exports = {notnull, checkPhone, checkPassword, checkUserInfo, checkRegister}